package com.yvan.serverless.utils;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Slf4j
public class JavaUtils implements InitializingBean, ApplicationContextAware {

    private ApplicationContext context;
    public static JavaUtils INSTANCE;

    @Override
    public void afterPropertiesSet() throws Exception {
        INSTANCE = this;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public Object getBean(String className) {
        return context.getBean(className);
    }

    public long newId() {
        long id = IdWorker.getId();
        return id;
    }

    public void saveFile(String path, String content) throws IOException {
        path = FileUtilExt.normalizePath(path);
        log.info("save file:\"{}\", content:{}", path, content.length());
        FileUtils.writeStringToFile(new File(path), content, StandardCharsets.UTF_8);
    }

    public String readFile(String path) throws IOException {
        path = FileUtilExt.normalizePath(path);
        log.info("read file:\"{}\"", path);
        return FileUtils.readFileToString(new File(path), StandardCharsets.UTF_8);
    }

    public String normalizePath(Object... args) {
        return FileUtilExt.normalizePath(args);
    }
}
